package com.lykj.llw.box.ui.activity

import android.content.ContentUris
import android.content.ContentValues
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.bytedance.applog.game.GameReportHelper
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.kwai.monitor.log.TurboAgent
import com.lykj.lib_base.app.BaseApplication
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.bus.FlowBus
import com.lykj.lib_base.constants.BConstants
import com.lykj.lib_base.data.bean.response.LoginResponse
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.R
import com.lykj.llw.box.databinding.ActMobileLoginBinding
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody

/**
 * ================================================
 * 手机号码和验证码方式登录
 * ================================================
 *
 * @author gosha
 * @date 2022/9/8-16:18
 */
class MobileLoginActivity : BaseActivity() {
    lateinit var binding: ActMobileLoginBinding

    private var isCheck = false

    private var mCountDownTimer: CountDownTimer? = null
    private val TAG = "Login"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActMobileLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initUI()
        initData()
        setListener()
    }

    override fun initUI() {
        ImmersionBar.with(this)
            .transparentBar()
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()
    }

    override fun initData() {
        FlowBus.with<String>(BConstants.BUS_KEY.LOGIN_SUCCESS).register(this) {
            finish()
        }
    }

    /**
     * 登录/注册
     */
    private fun loginOrRegister() {
        clearBodyParam()
        initBodyParam()
        bodyParams["tel"] = binding.etPhone.text.toString()
        bodyParams["yzm"] = binding.etVcode.text.toString()
        bodyParams["visitSource"] = "4"
//        bodyParams["channelId"] = "laiyuekj"

        RetrofitManager.instance.loginOrRegister(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@MobileLoginActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean =
                    GsonUtils.fromJson(responseBody, LoginResponse::class.java)

                if (null != bean.data) {
                    BaseApplication.instance?.setUserInfo(bean)

                    val jsonStr = GsonUtils.toJson(bean)
                    //存储用户信息到内存及本地
                    SPUtils.getInstance("user").put("userInfo", jsonStr, true)

                    //FIXME:是否注册
                    if (bean.data?.signup == true) {
                        GameReportHelper.onEventRegister("register", true)
                        LogUtils.e("---------巨量用户注册---已上报---------")
                        TurboAgent.onRegister()
                        LogUtils.e("---------快手用户注册---已上报---------")
                    }

                    FlowBus.with<String>(BConstants.BUS_KEY.LOGIN_SUCCESS).post(lifecycleScope, "")
                    ToastUtils.showShort(this@MobileLoginActivity, "登录成功")

                    //FIXME:写入测试数据到
                    val values = ContentValues()
                    values.put("name", bean.data?.username)
                    values.put("pwd", bean.data?.password)

                    val uri = "content://ProgramAndroid/person"
                    val deleteCount = contentResolver.delete(Uri.parse(uri), "", null)
                    if (deleteCount > 0) {
                        Log.e(TAG, "清除数据库用户数据成功")
                    }
                    var result = contentResolver.insert(Uri.parse(uri), values)
                    val addCount = ContentUris.parseId(result!!)
                    if (addCount > 0) {
                        Log.e(TAG, "添加数用户到数据库成功")
                    }

                    finish()
                }
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let { ToastUtils.showShort(this@MobileLoginActivity, it) }
            }

        }, bodyParams)
    }

    /**
     * 发送验证码
     */
    private fun sendVCode(phone: String) {
        RetrofitManager.instance.senVCode(object : CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@MobileLoginActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                ToastUtils.showShort(this@MobileLoginActivity, "发送验证码")
                binding.tvSendVcode.alpha = 0.7f
                mCountDownTimer = object : CountDownTimer(60 * 1000, 1000) {
                    override fun onTick(millisUntilFinished: Long) {
                        binding.tvSendVcode.text = "倒计时${(millisUntilFinished) / 1000}秒"
                    }

                    override fun onFinish() {
                        binding.tvSendVcode.text = "获取验证码"
                        binding.tvSendVcode.alpha = 1.0f
                    }
                }.start()
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let { ToastUtils.showShort(this@MobileLoginActivity, it) }
            }

        }, phone)
    }

    override fun setListener() {
        binding.ivBack.clickWithTrigger {
            finish()
        }

        binding.tvSendVcode.clickWithTrigger {
            if (binding.tvSendVcode.text.toString() != "获取验证码") {
                return@clickWithTrigger
            }
            if (binding.etPhone.text.toString().isNullOrBlank()) {
                ToastUtils.showShort(this, "请输入手机号码")
                return@clickWithTrigger
            }

            sendVCode(binding.etPhone.text.toString())
        }

        binding.tvBtnLoginOrRegister.clickWithTrigger {
            //非空检测
            if (binding.etPhone.text.toString().isNullOrBlank()) {
                ToastUtils.showShort(this, "请输入手机号码")
                return@clickWithTrigger
            }
            if (binding.etPhone.text.toString().length != 11) {
                ToastUtils.showShort(this, "请输入正确的手机号码")
                return@clickWithTrigger
            }

            if (binding.etVcode.text.toString().isNullOrBlank()) {
                ToastUtils.showShort(this, "请输入验证码")
                return@clickWithTrigger
            }
            if (!isCheck) {
                ToastUtils.showShort(this, "请阅读并同意相关协议")
                return@clickWithTrigger
            }

            loginOrRegister()
        }

        binding.tvLogin.clickWithTrigger {
//            startActivity(Intent(this, LoginActivity::class.java))
        }

        binding.ivCheck.clickWithTrigger {
            if (!isCheck) {
                binding.ivCheck.setImageResource(R.mipmap.ic_checked)
            } else {
                binding.ivCheck.setImageResource(R.mipmap.ic_uncheck)
            }

            isCheck = !isCheck
        }

        binding.tvUserProtocol.clickWithTrigger {
            val intent = Intent(this, CommonWebViewActivity::class.java)
            intent.putExtra("title", "用户协议")
            intent.putExtra("url", BConstants.USER_PROTOCOL)
            startActivity(intent)
        }

        binding.tvPrivacyProtocol.clickWithTrigger {
            val intent = Intent(this, CommonWebViewActivity::class.java)
            intent.putExtra("title", "隐私协议")
            intent.putExtra("url", BConstants.PRIVACY_PROTOCOL)
            startActivity(intent)
        }
    }

    override fun onDestroy() {
        mCountDownTimer?.cancel()
        mCountDownTimer = null
        removeDisposables(this@MobileLoginActivity)
        super.onDestroy()
    }
}